import { Controller, Get, Param, Res,HttpStatus  } from '@nestjs/common';
import { DownloadFileService } from './download-file.service';
import { Response } from 'express';
import { UserService } from 'src/user/user.service';
import * as fs from 'fs';
import * as path from 'path';

@Controller({
  path: 'download-file',
  version: '1'
})
export class DownloadFileController {
  constructor(
    private readonly downloadFileService: DownloadFileService,
    private readonly userService: UserService,
  ) { }
  @Get('avator/:id')
  async getavator(@Param('id') id: string, @Res() res: Response) {
    const userInfo = await this.userService.getuser(id)
    const avaterpath = userInfo.avater
    const filePath = path.join(__dirname, '..', '..', avaterpath);
    const filename = filePath.split('\\')[filePath.split('\\').length - 1]
    const fileStream = fs.createReadStream(filePath);
    res.setHeader('Content-Type', 'application/octet-stream');
    res.setHeader('Content-Disposition', `attachment; filename=${filename}`);
    fileStream.pipe(res);
    fileStream.on('error', (err) => {
      res.status(HttpStatus.INTERNAL_SERVER_ERROR).send(err.message);
    });

    fileStream.on('end', () => {
      res.end();
    });
  }
}
